import { navigate } from "../utils/fun.ts";
import { useConfig } from "./D8dConfigProvider.tsx";
import { useApiRequest } from "./useApiRequest.ts";
import { useEffect, useState } from "react";

export const useAlwaysLogin = () => {
  const { apiUrl, setUserInfo, setUserMenu, setToken } =
    useConfig();
  const { request } = useApiRequest();
  const [isLogin, setIsLogin] = useState(false);


  // 检查是否登录
  useEffect(() => {
    if (apiUrl.getUserInfo) {
      request({
        url: apiUrl.getUserInfo,
        method: "GET",
        headers: {
        },
        data: {},
        success(result) {
          if (result.code === 200) {
            setIsLogin(true);

            const res = result.data;
            setUserInfo(res);
            setUserMenu(res?.角色权限?.菜单列表);
            setToken(res.token);
          } else {
            setUserInfo(null);
            setUserMenu(null);
            setToken("");
            navigate("/");
          }
        },
        fail(error) {
          console.log(error);
        },
      });
    }
  }, []);

  // 返回一个布尔值，表示是否登录
  return isLogin;
};
